<template>
  <div class="content-area" >
    <el-container class="container-style">
      <el-container>
        <div style="width: 96%; margin: 0 auto; display: flex; flex-direction: column; align-items: center;">
          <div style="display: flex; align-items: center;">
            <h2>车位使用管理</h2>
          </div>
          <div class="community-select-wrapper">
            <el-select
                v-model="value"
                placeholder="选择某一小区查看"
                size="large"
                style="width: 240px;"
                @change="handleSelectChange"
            >
              <el-option
                  v-for="item in communityList"
                  :key="item.id"
                  :label="item.communityName"
                  :value="item.id"
              />
            </el-select>
            <el-button
                type="primary"
                size="large"
                style="margin-left: 10px;"
                @click="clearSelection"
            >
              清空选择
            </el-button>
          </div>

          <div style="background-color: white; padding: 20px; margin-top: 10px; width: 100%">
          <div class="table-header-container">
            <div class="search-container">
              <el-select v-model="searchOption" placeholder="请选择查询方式" class="search-select">
                <el-option label="按用户 ID查询" value="userId"></el-option>
                <el-option label="按车位 ID查询" value="parkingId"></el-option>
                <el-option label="按使用性质查询" value="useType"></el-option>
              </el-select>
              <el-input v-model="searchQuery"
                        :placeholder="
                  searchOption === 'useType'? '购买，月租，年租，临时' :
                  '请输入查询关键词'
                "
                        class="search-input"></el-input>

              <el-button type="primary" @click="searchParkingUse" class="search-button">查询</el-button>
            </div>
            <el-button type="primary" @click="handleCommunity">增加记录</el-button>
          </div>
          <table v-if="parkingUseForm && parkingUseForm.data && parkingUseForm.data.records"
                 style="text-align: center; width: 100%; border-collapse: collapse;">
            <thead>
            <tr style="border: 1px solid #eee;">
              <th style="width: 50px;  border: 1px solid #eee;">车位使用id</th>
              <th style="width: 100px;  border: 1px solid #eee;">用户id</th>
              <th style="width: 50px;  border: 1px solid #eee;">车牌号</th>
              <th style="width: 200px;  border: 1px solid #eee;">车位id</th>
              <th style="width: 50px;  border: 1px solid #eee;">使用性质</th>
              <th style="width: 50px;  border: 1px solid #eee;">总费用</th>
              <th style="width: 100px;  border: 1px solid #eee;">开始时间</th>
              <th style="width: 100px;  border: 1px solid #eee;">结束时间</th>
              <th style="width: 50px;  border: 1px solid #eee;">操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item, index) in parkingUseForm.data.records" :key="index" style="border: 1px solid #eee;">
              <td style="width: 50px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.id" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.userId" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 50px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.carNumber" :disabled="!item.isEdit" :class="{
        'normal-input-color':!item.isEdit,
        'edit-input-color': item.isEdit
      }" class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.parkingId" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 50px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.useType" :disabled="!item.isEdit" :class="{
        'normal-input-color':!item.isEdit,
        'edit-input-color': item.isEdit
      }" class="disabled-style"></el-input>
              </td>
              <td style="width: 50px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.totalFee" :disabled="!item.isEdit" :class="{
        'normal-input-color':!item.isEdit,
        'edit-input-color': item.isEdit
      }" class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.startTime" :disabled="!item.isEdit" :class="{
        'normal-input-color':!item.isEdit,
        'edit-input-color': item.isEdit
      }" class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.endTime" :disabled="!item.isEdit" :class="{
        'normal-input-color':!item.isEdit,
        'edit-input-color': item.isEdit
      }" class="disabled-style"></el-input>
              </td>
              <td style="width: 50px; height: 40px; border: 1px solid #eee;">
                <div class="button-group">
                  <template v-if="!item.isEdit">
                    <el-button type="success" @click="saveItem(item)">修改记录</el-button>
                  </template>

                  <template v-if="item.isEdit&&parkingUseForm && parkingUseForm.data && parkingUseForm.data.records.some(item => item.isEdit)">
                    <el-button type="success" @click="handleSaveEdit">保存修改</el-button>
                    <el-button type="default"  @click="handleCancelEdit" style="margin-left: 10px">取消修改</el-button>
                  </template>
                </div>
              </td>
            </tr>
            </tbody>
          </table>
          <div v-else-if="errorMessage">{{ errorMessage }}</div>
        </div>
          <div style="display: flex; justify-content: center; width: 100%;">
            <el-pagination
                class="footer"
                v-if="parkingUseForm && parkingUseForm.data"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[8, 10, 12]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="parkingUseForm.data.total"
            >
            </el-pagination>
          </div>
        </div>
      </el-container>
    </el-container>
    <el-dialog v-model="addDialogFormVisible" title="增加车位使用记录" width="500">
      <el-form :model="addForm">
        <el-form-item label="用户id" :label-width="formLabelWidth">
          <el-input v-model="addForm.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="车牌号" :label-width="formLabelWidth">
          <el-input v-model="addForm.carNumber" placeholder="请输入车牌号" />
        </el-form-item>
        <el-form-item label="车位id" :label-width="formLabelWidth">
          <el-input v-model="addForm.parkingId" placeholder="请输入车位id" />
        </el-form-item>
        <el-form-item label="使用类型" :label-width="formLabelWidth">
          <el-select v-model="addForm.useType" placeholder="请选择使用类型">
            <el-option v-for="option in parkingUseStatusOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="总费用" :label-width="formLabelWidth">
          <el-input v-model="addForm.totalFee" placeholder="请输入总费用" />
        </el-form-item>
        <el-form-item label="开始使用时间" :label-width="formLabelWidth">
          <el-date-picker
              v-model="this.addForm.startTime"
              type="datetime"
              placeholder="请选择开始使用时间"
              :picker-options="{
        shortcuts: false,
        format: 'yyyy-MM-dd HH:mm:ss',
        valueFormat: 'yyyy-MM-dd HH:mm:ss',
        selectableRange: '00:00:00 - 23:59:59'
      }"
              :rules="{ required: true, message: '请选择开始使用时间', trigger: 'change' }"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="使用结束时间" :label-width="formLabelWidth">
          <el-date-picker
              v-model="this.addForm.endTime"
              type="datetime"
              placeholder="请选择开始使用时间"
              :picker-options="{
        shortcuts: false,
        format: 'yyyy-MM-dd HH:mm:ss',
        valueFormat: 'yyyy-MM-dd HH:mm:ss',
        selectableRange: '00:00:00 - 23:59:59'
      }"
              :rules="{ required: true, message: '请选择开始使用时间', trigger: 'change' }"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="handleConfirm">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import moment from'moment';
import * as echarts from "echarts";

export default {
  data() {
    return {
      userName: localStorage.getItem('adminName') || '',
      errorMessage: '',
      currentPage: 1,
      pageSize: 12,
      addDialogFormVisible: false,
      addForm: {
        userId: "",
        carNumber: "",
        parkingId: "",
        useType: "",
        totalFee: "",
        startTime: "",
        endTime: ""
      },
      showDialog: false,
      parkingUseForm: {
        id: "",
        communityId: this.communityId,
        userId: "",
        carNumber: "",
        parkingId: "",
        useType: "",
        totalFee: "",
        startTime: "",
        endTime: ""
      },
      newParkingUse: {},
      parkingUseStatusOptions: [
        { label: '购买', value: '购买' },
        { label: '月租', value: '月租' },
        { label: '年租', value: '年租' },
        { label: '临时', value: '临时' }
      ],
      isEdit: false,
      saveEditId: null,
      originalInfo: null,
      searchQuery: '',
      formLabelWidth: '120px',
      searchOption: "",
      purchasedCount: "",
      monthlyRentedCount: "",
      yearlyRentedCount: "",
      temporaryCount: "",
      communityId: "",
      value: null,
      communityList: null
    };
  },
  setup() {
    const router = useRouter();
    return {
      router
    };
  },
  methods: {
    clearSelection() {
      // 清空选择
      this.value = null;
      this.communityId = "";
      // 重新加载默认数据
      this.fetchData();
    },
    handleSelectChange(value) {
      this.communityId = value;
      this.fetchData();
    },
    async fetchCommunityList() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未获取到token，请重新登录');
          return;
        }
        const response = await axios.get('/api/community/search', {
          headers: {
            Authorization: token
          }
        });
        console.log(response)
        this.communityList = response.data.data;
        console.log('this.community',this.communityList)
      } catch (error) {
        ElMessage.error('获取小区列表时出错：' + error.message);
      }
    },
    handleCommunity(){
      if(this.communityId) {
        this.addDialogFormVisible = true;
      }else{
        ElMessage.info('请先选择小区')
      }
    },
    pageChange(url) {
      this.$router.push(url);
    },
    handleLogout() {
      console.log('执行退出登录操作');
    },
    async fetchData() {
      try {
        const token = localStorage.getItem('token');
        let url = '/api/parking-use/page';
        let params = {
          current: this.currentPage,
          size: this.pageSize,
          communityId: this.communityId
        };
         if(this.searchOption == 'userId'){
          params.userId = this.searchQuery;
        }else if(this.searchOption == 'parkingId'){
          params.parkingId = this.searchQuery;
        }else if(this.searchOption == 'useType'){
          params.useType = this.searchQuery;
        }
        const response = await axios.get(url, {
          headers: {
            Authorization: token
          },
          params: params
        });
         console.log('parkingUse',response)
        this.parkingUseForm = response.data;
        this.originalInfo = {...this.parkingUseForm} ;
        if (this.parkingUseForm && this.parkingUseForm.data && this.parkingUseForm.data.records) {
          this.parkingUseForm.data.records.forEach(item => {
            item.isEdit = false;
          });
        }
        console.log(response.data);
      } catch (error) {
        ElMessage.error('获取车位使用列表数据统计失败:', error);
        this.errorMessage = '获取数据失败，请稍后重试';
      }
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
    async fetchStatusCounts() {
      this.showDialog = true;
      this.purchasedCount = await this.getRecordCountByStatus(this.communityId, '购买');
      this.monthlyRentedCount = await this.getRecordCountByStatus(this.communityId, '月租');
      this.yearlyRentedCount = await this.getRecordCountByStatus(this.communityId, '年租');
      this.temporaryCount = await this.getRecordCountByStatus(this.communityId, '临时');
      this.drawPieChart();
    },
    async getRecordCountByStatus(communityId, useType) {
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get('/api/parking-use/page', {
          headers: {
            Authorization: token
          },
          params: {
            current: this.currentPage,
            size: this.pageSize,
            communityId: communityId,
            useType: useType
          }
        });
        return response.data.data.total;
      } catch (error) {
        ElMessage.error('获取对应状态记录数量失败:', error);
        this.errorMessage = '获取数据失败，请稍后重试';
        return 0;
      }
    },
    drawPieChart() {
      const chartDom = document.getElementById('barChart');
      const myChart = echarts.init(chartDom);
      const option = {
        title: {
          text: '车位使用性质状态分布',
          subtext: `总记录数: ${this.purchasedCount + this.monthlyRentedCount + this.yearlyRentedCount + this.temporaryCount}`,
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['购买', '月租', '年租', '临时']
        },
        series: [
          {
            name: '状态分布',
            type: 'pie',
            radius: '50%',
            data: [
              { value: this.purchasedCount, name: '购买' },
              { value: this.monthlyRentedCount, name: '月租' },
              { value: this.yearlyRentedCount, name: '年租' },
              { value: this.temporaryCount, name: '临时' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      myChart.setOption(option);
    },
    handleConfirm() {
      this.confirmAdd();
    },
    async confirmAdd() {
      try {
        const token = localStorage.getItem('token');
        const startTime = moment(this.addForm.startTime).format('YYYY-MM-DD HH:mm:ss');
        const endTime = moment(this.addForm.endTime).format('YYYY-MM-DD HH:mm:ss');
        const response = await axios.post(`/api/parking-use/${this.addForm.userId}`, null, {
          headers: {
            Authorization: token
          },
          params: {
            userId: this.addForm.userId,
            carNumber: this.addForm.carNumber,
            parkingId: this.addForm.parkingId,
            useType: this.addForm.useType,
            totalFee: this.addForm.totalFee,
            startTime: startTime,
            endTime: endTime
          }
        });
        if (response.data.code === 200) {
          ElMessage.success('增加车位使用记录成功');
          this.addDialogFormVisible = false;
          this.fetchData();
        } else {
          ElMessage.error('增加车位使用记录失败,请输入正确信息');
        }
      } catch (error) {
        ElMessage.error('增加车位使用记录时出错：' + error.message);
      }
    },
    saveItem(item) {
      item.isEdit = true;
      this.saveEditId = item.id;
    },
    async handleSaveEdit() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          throw new Error('token不存在');
        }
        // 找到当前正在编辑的那一行数据
        const currentEditedItem = this.parkingUseForm.data.records.find(
            item => item.id === this.saveEditId
        );
        if (!currentEditedItem) {
          ElMessage.error('未找到当前编辑的车位使用记录');
          return;
        }
        const response = await axios.put(
            `/api/parking-use/${this.saveEditId}`,
            null,
            {
              headers: {
                Authorization: token
              },
              params:{
                id: currentEditedItem.id,
                userId: currentEditedItem.userId,
                carNumber: currentEditedItem.carNumber,
                parkingId: currentEditedItem.parkingId,
                useType: currentEditedItem.useType,
                totalFee: currentEditedItem.totalFee,
                startTime: currentEditedItem.startTime,
                endTime: currentEditedItem.endTime
              }
            }
        );
        if (response.data.code === 200) {
          this.fetchData();
          this.isEdit = false;
          ElMessage.success('车位使用信息修改成功');
        } else {
          ElMessage.error('车位使用信息修改失败，请输入正确信息');
        }
      } catch (error) {
        ElMessage.error('车位使用信息修改时出错：' + error.message);
      }
    },
    handleCancelEdit() {
      this.parkingUseForm = {...this.originalInfo };
      if (this.parkingUseForm && this.parkingUseForm.data && this.parkingUseForm.data.records) {
        this.parkingUseForm.data.records.forEach(item => {
          item.isEdit = false;
        });
      }
      this.isEdit = false;
    },
    async searchParkingUse() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未授权，请先登录');
          return;
        }
         if (this.searchOption === 'userId') {
          const response = await axios.get('/api/parking-use/page', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              communityId: this.communityId,
              userId: this.searchQuery
            }
          });
          if (response.data.code === 200) {
            this.parkingUseForm = response.data;
            this.originalInfo = {...this.parkingUseForm };
          } else {
            ElMessage.error('查询车位使用信息失败');
          }
        }else if (this.searchOption === 'parkingId') {
          const response = await axios.get(`/api/parking-use/page`, {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              communityId: this.communityId,
              parkingId: this.searchQuery
            }
          });
          if (response.data.code === 200) {
            this.parkingUseForm = response.data;
            this.originalInfo = {...this.parkingUseForm };
          } else {
            ElMessage.error('查询车位使用信息失败');
          }
        }else if (this.searchOption === 'useType') {
          const response = await axios.get(`/api/parking-use/page`, {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              communityId: this.communityId,
              useType: this.searchQuery
            }
          });
          if (response.data.code === 200) {
            this.parkingUseForm= response.data;
            this.originalInfo = {...this.parkingUseForm };
          } else {
            ElMessage.error('查询车位使用信息失败');
          }
        }
      }catch (error) {
        ElMessage.error('网络错误，请稍后重试');
      }
    }
  },
  mounted() {
    this.fetchData();
    this.fetchCommunityList();
  }
};
</script>

<style scoped>

.footer {
  margin-top: 20px;
  text-align: center;
  padding: 10px;
  transition: margin-left 0.3s;
}

.container-style {
  height: 100%;
}

.header-style {
  background-color: rgb(204, 225, 234);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.footer-style {
  text-align: center;
  background-color: rgba(129, 175, 184, 0.83);
}

.content-area {
  background-color: #f2f5fa;
  padding: 20px;
  height: calc(100vh - 120px); /* 50(header) + 10(footer padding top) + 60(footer height & bottom margin) */
  overflow-y: auto; /* 启用滚动条 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
}

.community-select-wrapper {
  display: flex;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: center;
  align-items: center;
}

.search-input {
  flex: 1;
  width: 250px;
  margin-right: 10px;
}

.search-button {
  min-width: 80px;
}

.table-header-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 10px;
}

.disabled-style {
  cursor: default;
}


.form-label-width {
  width: 120px;
}

.normal-input-color {
  color: inherit;
}

.edit-input-color {
  color: #ccc;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 5px;
}

.search-input {
  flex: 1;
  width: 350px;
  margin-right: 10px;
}

.search-select {
  flex: 1;
  width: 30px;
}

</style>